using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace WhsFacebook.Net.Contracts
{
    public sealed class WhsFacebookServiceClientFactory : IDisposable
    {
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(WhsFacebookServiceClientFactory));
        private ChannelFactory<IWhsFacebookService> _factory;

        public IWhsFacebookService CreateChannel()
        {
            return _factory.CreateChannel();
        }

        public Uri Endpoint
        {
            get { return _factory.Endpoint.Address.Uri; }
        }

        public CommunicationState State
        {
            get { return _factory.State; }
        }

        public WhsFacebookServiceClientFactory()
        {
            // prepare
            var ep = new Uri(Properties.Settings.Default.WhsFacebookServiceEndpoint);

            var isHttps = (ep.Scheme == "https");

            // create binding
            var binding = new BasicHttpBinding()
            {
                MaxReceivedMessageSize = (1024 * 1024), // 1MB
                MaxBufferPoolSize = (8 * 1024 * 1024), // 8MB
                OpenTimeout = new TimeSpan(0, 0, 10),   // 1 minute
                CloseTimeout = new TimeSpan(0, 0, 10),  // 1 minute
                ReceiveTimeout = new TimeSpan(0, 10, 0),// 10 minutes
                SendTimeout = new TimeSpan(0, 10, 0),   // 10 minutes
                MessageEncoding = WSMessageEncoding.Mtom,
                TransferMode = TransferMode.Streamed,
            };

            if (isHttps)
            {
                binding.Security.Mode = BasicHttpSecurityMode.Transport;
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            }

            // create factory
            _factory = new ChannelFactory<IWhsFacebookService>(
                binding,
                new EndpointAddress(ep)
                );

            _factory.Faulted += new EventHandler(factory_Faulted);

            _factory.Open();
        }

        private void factory_Faulted(object sender, EventArgs e)
        {
            _log.Warn("WCF client faulted");
        }

        public void Dispose()
        {
            if (_factory != null)
            {
                _factory.Close();
            }
        }

    }
}